package com.sibu.yx.promotion.web.support.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.filter.DelegatingFilterProxy;

import com.doubo.common.pattern.PatternMatcher;
import com.doubo.common.pattern.ServletPathMatcher;
import com.doubo.security.util.WebUtils;

/**
 * Created with IntelliJ IDEA.
 * User: qiujingwang
 * Date: 2016/11/14
 * Description: 增加isExclusion方法，过滤url
 *
 <init-param>
    <param-name>exclusions</param-name>
    <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
 </init-param>
 *
 */
public class CustomDelegatingFilterProxy extends DelegatingFilterProxy {

    public static final String PARAM_NAME_EXCLUSIONS = "exclusions";

    protected String contextPath;

    /**
     * PatternMatcher used in determining which paths to react to for a given request.
     */
    protected PatternMatcher pathMatcher = ServletPathMatcher.getInstance();

    private Set<String> excludesPattern;

    @Override
    protected void invokeDelegate(Filter delegate, ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String requestURI = getRequestURI(httpRequest);

        if (isExclusion(requestURI)) {
            filterChain.doFilter(request, response);
            return;
        }
        super.invokeDelegate(delegate, request, response, filterChain);
    }

    public boolean isExclusion(String requestURI) {
        if (excludesPattern == null) {
            return false;
        }
        if (contextPath != null && requestURI.startsWith(contextPath)) {
            requestURI = requestURI.substring(contextPath.length());
            if (!requestURI.startsWith("/")) {
                requestURI = "/" + requestURI;
            }
        }

        for (String pattern : excludesPattern) {
            if (pathMatcher.matches(pattern, requestURI)) {
                return true;
            }
        }

        return false;
    }

    public String getRequestURI(HttpServletRequest request) {
        return request.getRequestURI();
    }

    @Override
    public void initFilterBean() throws ServletException {
        super.initFilterBean();
        {
            String exclusions = getFilterConfig().getInitParameter(PARAM_NAME_EXCLUSIONS);
            if (exclusions != null && exclusions.trim().length() != 0) {
                excludesPattern = new HashSet<String>(Arrays.asList(exclusions.split("\\s*,\\s*")));
            }
        }

        this.contextPath = WebUtils.getContextPath(getFilterConfig().getServletContext());

    }
}
